import { useIntersectionObserver, useIntervalFn } from '@vueuse/core';
import { onMounted, ref } from 'vue';

// 接收一个回调函数，返回一个ref引用
// 功能：当ref引用的dom处于可见状态时，调用一次回调函数
export function useLazyDate( fn:() => void ) {
  // 当整个区块处于可见状态时，才发ajax
  const target = ref(null)
  onMounted(() => {
    const {stop} = useIntersectionObserver(target.value, ([{isIntersecting}]) => {
      if(isIntersecting) {
        fn()
        // 停止监听
        stop()
      }
    })
  })
  return target
}

// 倒计时
export function useCountDoen() {
  const counter = ref(0)
  const {pause, resume} = useIntervalFn(() => {
    if(counter.value === 0) {
      // 清空定时器
      pause()
    } else {
      counter.value--
    }
  }, 1000, { immediate: false })

  const start = (num: number) => {
    counter.value = num
    resume()
  }

  return { counter, start }
}